package com.yoga.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yoga.dao.CourseMapper;
import com.yoga.dao.ReservationMapper;
import com.yoga.model.Course;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author yan
 * @date 2025/8/30
 */
@Service
public class CourseStatusUpdateService {
    private CourseMapper courseMapper;
    private ReservationMapper reservationMapper;

    @Autowired
    public void setCourseMapper(CourseMapper courseMapper) {
        this.courseMapper = courseMapper;
    }

    @Autowired
    public void setReservationMapper(ReservationMapper reservationMapper) {
        this.reservationMapper = reservationMapper;
    }

    @Scheduled(cron = "0 0/10 6-23 * * ?")
    public void updateCourseStatus() {
        //查询正在进行的课程
        QueryWrapper<Course> qw = new QueryWrapper<>();
        qw.le("schedule", LocalDateTime.now());//已经开始
        List<Course> courses = courseMapper.selectList(qw);
        for (Course course : courses) {
            //计算课程结束时间
            if (course.getDuration() != null && course.getSchedule() != null) {
                LocalDateTime endTime = course.getSchedule().plusMinutes(course.getDuration());
                if (LocalDateTime.now().isAfter(endTime)) {
                    //更新状态
                    updateCourseAndMemberStatus(course);
                }
            }
        }
    }

    /**
     * 更新课程和会员状态
     */
    private void updateCourseAndMemberStatus(Course course) {
        int count = reservationMapper.updateStatusByCourseId(course.getCourseId(), 1);
        System.out.println("课程 " + course.getCourseName() + " 已自动结束，更新了 " + count + " 条预约记录");
    }
}
